package com.cheer.ba.view.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.smileyloadingview.SmileyHeaderView;
import com.cheer.ba.R;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.widget.ProgressWebView;

import butterknife.BindView;

/**
 * 刷新的H5
 */
public class CommH5RefreshAty extends BaseCommAty {

    @BindView(R.id.id_h5_refresh_view)
    XRefreshView mXRefreshView;
    //进度条
    @BindView(R.id.id_webview)
    ProgressWebView webView;
    //错误url
    @BindView(R.id.id_error_ulr_txt)
    TextView mTxtErrorUrl;
    //路径地址
    private String url;
    //标题名
    private String titleName;

    /**
     * 启动刷新的h5界面
     *
     * @param url       跳转链接
     * @param titleName 标题
     */
    public static void startCommH5RefreshAty(Activity activity, String url, String titleName) {
        Intent intent = new Intent(activity, CommH5WithTitleAty.class);
        intent.putExtra(IntentKey.General.KEY_URL, url);
        intent.putExtra(IntentKey.General.KEY_DES, titleName);
        activity.startActivity(intent);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        url = getIntent().getStringExtra(IntentKey.General.KEY_URL);
        titleName = getIntent().getStringExtra(IntentKey.General.KEY_DES);
    }

    @Override
    protected boolean isStatusBarTint() {
        return !StringUtils.isEmpty(titleName);
    }

    @Override
    protected boolean isTitleBarShow() {
        return !StringUtils.isEmpty(titleName);
    }

    @Override
    protected boolean isSupportSwipeback() {
        return false;
    }

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_comm_h5_refresh, null, false));
    }

    @Override
    public void initView() {
        setXRefreshView(mXRefreshView, true, false, true, false, new SmileyHeaderView(aty), null);

        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(true);
        //支持屏幕缩放
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        //不显示webview缩放按钮
        settings.setDisplayZoomControls(false);
        settings.setLoadWithOverviewMode(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.setVerticalScrollBarEnabled(false);
        webView.setVerticalScrollbarOverlay(false);
        webView.setHorizontalScrollBarEnabled(false);
        webView.setHorizontalScrollbarOverlay(false);
        webView.setOverScrollMode(View.OVER_SCROLL_NEVER);

        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimetype,
                                        long contentLength) {
                if (url != null && url.startsWith("http://"))
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri
                            .parse(url)));
            }
        });

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                if (!StringUtils.isEmpty(view.getTitle())) {
                    setTitleText(view.getTitle());
                } else {
                    setTitleText(titleName);
                }
                mXRefreshView.stopRefresh();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                mXRefreshView.stopRefresh();
                ToastUtil.showToast("加载失败，请检查网络。");
            }
        });
    }

    @Override
    public void initData() {
        mXRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(final boolean isPullDown) {
                if (!StringUtils.isEmpty(url) && (url.startsWith("http://") || url.startsWith("https://"))) {
                    webView.loadUrl(url);
                } else {
                    mTxtErrorUrl.setVisibility(View.VISIBLE);
                    webView.setVisibility(View.GONE);
                    if (StringUtils.isEmpty(url)) {
                        mTxtErrorUrl.setText("跳转链接为空");
                    } else {
                        mTxtErrorUrl.setText(url);
                    }
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mXRefreshView.stopRefresh();
                        }
                    }, 4000);
                }
            }
        });
    }
}
